<?php

class Application_Model_ProfitMapper extends Application_Model_Mapper
{
    const JANUARY   = 1;
    const FEBRUARY  = 2;
    const MARСH     = 3;
    const APRIL     = 4;
    const MAY       = 5;
    const JUNE      = 6;
    const JULE      = 7;
    const AUGUST    = 8;
    const SEPTEMBER = 9;
    const OCTOBER   = 10;
    const NOVEMBER  = 11;
    const DECEMBER  = 12;

    const LIMIT_PROFITS_DEFAULT    = 5;
    const LIMIT_PROFITS_TEN_YEARS  = 10;
    const LIMIT_PROFITS_ALL        = 100;

    const BY_DAYS   = 1;
    const BY_MONTH  = 2;

    const STATS_YEAR_CURRENT = 10;
    const STATS_YEAR_PREVIOUS = 11;
    const STATS_YEAR_BEST = 12;

    const STATS_MONTH_CURRENT = 1;
    const STATS_MONTH_PREVIOUS = 2;
    const STATS_MONTH_BEST = 3;

    static $month = array();

    static $stats = array(
        self::STATS_YEAR_CURRENT   => 'В текущем',
        self::STATS_YEAR_PREVIOUS  => 'В прошлом',
        self::STATS_YEAR_BEST      => 'Лучший доход',
        self::STATS_MONTH_CURRENT  => 'В текущем',
        self::STATS_MONTH_PREVIOUS => 'В прошлом',
        self::STATS_MONTH_BEST     => 'Лучший доход',
    );

    /**
     *
     * массив вида:
     *
     * год => планы дохода на этот год
     *
     */

    static $profitPlane = array(
        2013 => 840000
    );

    public function getMonthName($id)
    {
        if (!self::$month) {
            self::$month = array(
                self::JANUARY   => 'Январь',
                self::FEBRUARY  => 'Февраль',
                self::MARСH     => 'Март',
                self::APRIL     => 'Апрель',
                self::MAY       => 'Май',
                self::JUNE      => 'Июнь',
                self::JULE      => 'Июль',
                self::AUGUST    => 'Август',
                self::SEPTEMBER => 'Сентябрь',
                self::OCTOBER   => 'Октябрь',
                self::NOVEMBER  => 'Ноябрь',
                self::DECEMBER  => 'Декабрь',
            );
        }

        return self::$month[$id];
    }

    public function __construct()
    {
        parent::__construct(new Application_Model_DbTable_Profits(), new Application_Model_Profit());
        $this->tableMonth = new Application_Model_DbTable_ProfitsMonth();
    }

    public function getStatsProfit()
    {
        $currentMonth = date('m');
        $currentYear = date('Y');

        $previousMonth = ($currentMonth == 1) ? 12 : $currentMonth - 1;
        $previousYear = $currentYear - 1;
        $statsProfit = array();

        $statsProfit[self::STATS_MONTH_PREVIOUS] = $this->getMonthProfit(($currentMonth == 1) ? $previousYear : $currentYear, $previousMonth);
        $statsProfit[self::STATS_MONTH_CURRENT]  = $this->getMonthProfit($currentYear, $currentMonth);
        $statsProfit[self::STATS_MONTH_BEST]     = $this->getBestProfit('month');
        $statsProfit[self::STATS_YEAR_CURRENT]   = $this->getYearProfit($currentYear);
        $statsProfit[self::STATS_YEAR_PREVIOUS]  = $this->getYearProfit($previousYear);
        $statsProfit[self::STATS_YEAR_BEST]      = $this->getBestProfit('year');

        return $statsProfit;
    }

    public function getMonthProfit($year, $month)
    {
        /**
         * TODO кеширование данных
         */
        $select = $this->table->select()->where('profit_date >= ?', $year . '-' . $month . '-1')->where('profit_date <= ?', $year . '-' . $month . '-31');
        $profits = $this->fetchAll($select);

        $summ = 0;
        foreach ($profits as $profit) {
            /** @var $profit Application_Model_Profit */

            if (isset($summ)) {
                $summ += $profit->getProfitSumm();
            } else {
                $summ = $profit->getProfitSumm();
            }
        }

        return $summ;
    }


    public function getYearProfit($year)
    {
        /**
         * TODO кеширование данных
         */
        $select = $this->table->select()->where('profit_date >= ?', $year . '-01-1')->where('profit_date <= ?', $year . '-12-31');
        $profits = $this->fetchAll($select);

        $summ = 0;
        foreach ($profits as $profit) {
            /** @var $profit Application_Model_Profit */
            $summ += $profit->getProfitSumm();
        }

        return $summ;
    }


    public function getBestProfit($period)
    {
        $profit = 0;
        $select = $this->tableMonth->select();

        /**
         * TODO кеширование данных
         */
        switch ($period) {
            case "month":
                $select->from($this->tableMonth, array('profit_summ', new Zend_Db_Expr('`month`'), new Zend_Db_Expr('`year`')))->order('profit_summ desc')->limit(1,0);
                $row = $this->tableMonth->fetchRow($select)->toArray();

                $profit = array(
                    'summ'  => $row['profit_summ'],
                    'month' => $row['month'],
                    'year'  => $row['year']
                );

                break;
            case "year":
                $select->from($this->tableMonth, array('sum(`profit_summ`) as max', 'year'))->group('year')->order('max desc');
                $row = $this->tableMonth->fetchRow($select)->toArray();
                $profit = array(
                    'summ'  => $row['max'],
                    'year'  => $row['year']
                );
                break;
        }

        return $profit;
    }

    /**
     * разбирает массив моделей Application_Model_Profit в массив для построения графика
     *
     * @return array
     */
    public function getDataForHightCharts($period = self::LIMIT_PROFITS_DEFAULT)
    {
        $result = array();
        $profits = $this->getCollection(array("(YEAR(CURRENT_DATE ) - YEAR( profit_date )) < {$period}"), 'profit_date ASC');

        foreach ($profits as $profit) {
            /** @var $profit Application_Model_Profit */
            $result[$profit->getYear()][] = array(
                'id'  => $profit->getProfitId(),
                'year'  => $profit->getYear(),
                'month' => $profit->getMonth(),
                'day'   => $profit->getDay(),
                'summ'  => $profit->getProfitSumm()
            );
        }

        return $result;

    }
}
